<?php

/***************************************************************/
/* Class SeniorityList - This class is used create and view    */
/* seniority lists                                             */
/***************************************************************/

class SeniorityList {
	var $newestList;
	var $newestGroupID;
	var $newestGroupDate;
	
	function generateList(){
		if ($this->checkActiveDrivers()){
			$group_id = $this->createListGroup();
			$lastDriverRanks = $this->getLastList();
			$query = "SELECT SUM(t_seniority.points) AS totalPoints, t_drivers.firstname, t_drivers.lastname, t_drivers.driver_id FROM t_drivers LEFT JOIN t_seniority ON t_drivers.driver_id = t_seniority.driver_id WHERE (t_drivers.active = '1' AND t_drivers.durational = '0'" . EXCLUDE_QUERY . ") GROUP BY t_drivers.driver_id ORDER BY totalPoints DESC, lastname ASC";
			$result = mysql_query($query);
			$i = 1;
			while($data = mysql_fetch_array($result)){
				$points = $data['totalPoints'];
				if (empty($points)) $points = 0;
				$driver_id = $data['driver_id'];
				$name = $data['firstname'] . " " . $data['lastname'];
				if (!empty($lastDriverRanks[$driver_id])) $lastRank = $lastDriverRanks[$driver_id];
				else $lastRank = 0;
				$insertQuery = "INSERT INTO t_seniority_list SET driver_id = '" . $driver_id . "', rank = '" . $i . "', prev_rank = '" . $lastRank . "', points = '" . $points . "', group_id = '" . $group_id . "'";
				$insertResult = mysql_query($insertQuery);
				$i++;
			}
			$msg = "The seniority list has successfully been generated.<br><br><a href=\"/seniorityList.php?listid=" . $group_id . "\" target=\"_blank\">View Seniority List</a>";
		} else $msg = "There are no active drivers. Seniority list cannot be generated.";
		return $msg;
	}
	
	function createListGroup(){
		$query = "INSERT INTO t_seniority_group  SET generated_by  = " . $_SESSION['driver_id'];
		$result = mysql_query($query);
		return mysql_insert_id();
	}
	
	function checkActiveDrivers(){
		$query = "SELECT * FROM t_drivers WHERE (active = '1' AND durational = '0'" . EXCLUDE_QUERY . ")";
		$result = mysql_query($query);
		if (mysql_num_rows($result) == 0) return false;
		else return true;
	}
	
	function getLastList(){
		if (!empty($this->newestGroupID)){
			$query = "SELECT * FROM t_seniority_list WHERE group_id = '" . $this->newestGroupID . "'";
			$result = mysql_query($query);
			if (mysql_num_rows($result) == 0) return false;
			else {
				while ($data = mysql_fetch_array($result)){
					$driverid = $data['driver_id'];
					$drivers[$driverid] = $data['rank'];
				}
				return $drivers;
			}
		} else return false;
	}
	
	function getNewestGroup(){
		$query = "SELECT date_format(timestamp, '%M %D, %Y at %H:%i') AS timestamp, group_id FROM t_seniority_group ORDER BY timestamp DESC LIMIT 1";
		$result = mysql_query($query);
		if (mysql_num_rows($result) == 1) {
			$this->newestGroupID = mysql_result($result, 0, 'group_id');
			$this->newestGroupDate = mysql_result($result, 0, 'timestamp');
		}
	}
	
	function displayLists(){
		$query = "SELECT group_id, date_format(timestamp, '%M %D, %Y at %H:%i') AS timestamp FROM t_seniority_group ORDER BY timestamp DESC";
		$result = mysql_query($query);
		if (mysql_num_rows($result) == 0) echo "No seniority lists have been generated.";
		else
			while ($data = mysql_fetch_array($result)){
				echo "<a href=\"/seniorityList.php?listid=" . $data['group_id'] . "\" target=\"_blank\">" . $data['timestamp'] . "</a><br>";
			}
	}
	
	/*
	function getNewestSeniorityList(){
		$query = "SELECT id FROM t_seniority_group ORDER BY timestamp DESC LIMIT 1";
		$result = mysql_query($query);
		if (mysql_num_rows($result) == 1) $gid = mysql_result($result, 0);
		else return false;
	
		$query = "SELECT driver_id, rank FROM t_seniority_list WHERE group_id = '" . $gid . "'";
		$result = mysql_query($query);
		if (mysql_num_rows($result) == 0) return false;
		else {
			while($data = mysql_fetch_array($result)){
				$driver = $data['driver_id'];
				$this->newestList[$driver] = $data['rank'];
			}
		}
	}
	*/

	function getNewestSeniorityListDate(){ return $this->newestGroupDate; }
}


/***************************************************************/
/* Class PointsAdd - This class is used to create adjustments  */
/* for drivers for happy write ups, write ups, etc             */
/***************************************************************/

class PointsAdd {
	var $driverid;
	var $adjustmentReason;
	var $points;
	var $resetFields;
	var $sendEmail;
	var $sendMessage;
	var $emailSubject;
	var $emailBody;
	var $errors; 
	var $entryBy;
	
	function displayActiveDriverList($selected = ""){
		$query = "SELECT * FROM t_drivers WHERE (active = '1' AND durational = '0'" . EXCLUDE_QUERY . ") ORDER BY lastname ASC";
		$result = mysql_query($query);
		echo "<select name=\"driver\" onchange=\"updateExtraFields()\">\n";
		while ($data = mysql_fetch_array($result)){
			echo "<option value=\"" . $data['driver_id'] . "\"";
			if ($selected == $data['driver_id']) echo " selected=\"selected\"";
			echo ">" . $data['lastname'] . ", " . $data['firstname'] . "</option>\n";
		}
		echo "</select>\n";
	}

	function displayActiveDriverJavascript(){
		echo "<script type=\"text/javascript\">\n";
		echo "var drivers = new Array();\n";
		$query = "SELECT * FROM t_drivers WHERE (active = '1' AND durational = '0'" . EXCLUDE_QUERY . ") ORDER BY lastname ASC";
		$result = mysql_query($query);
		while ($data = mysql_fetch_array($result)){
			echo "drivers[" . $data['driver_id'] . "] = \"" . $data['firstname'] . "\";\n";
		}
		echo "</script>\n";

	}
	
	function getData(){
		$this->driverid = $_POST['driver'];
		$this->adjustmentReason = $_POST['reason'];
		$this->points = $_POST['points'];
		$this->sendEmail = $_POST['sendEmail'];
		$this->sendMessage = $_POST['sendMessage'];
		$this->resetFields = $_POST['resetFields'];
		$this->emailSubject = $_POST['emailSubject'];
		$this->emailBody = $_POST['emailBody'];
	}
	
	function validateData(){
		if($this->entryBy <= 0) $this->errors["noEntryBy"] = true;
		if (empty($this->adjustmentReason)) $this->errors['noReason'] = "Please enter the reason for the adjustment.";
		if ($this->points == "0") $this->errors['noPoints'] = "The points value cannot equal 0.";
		if (!is_numeric($this->points)) $this->errors['notNumeric'] = "Points must be numerical.";
		if ($this->sendEmail || $this->sendMessage){
			if (empty($this->emailSubject)) $this->errors['noSubject'] = "You must enter a subject for the email/message.";
			if (empty($this->emailBody)) $this->errors['noBody'] = "You must enter a body for the email/message.";
		}
		if (empty($this->errors)) return true;
		else return false;
	}
	
	function insertData(){
		$query = "INSERT INTO t_seniority SET driver_id = '" . $this->driverid . "', points = '" . $this->points . "', entry_by = '" . $this->entryBy . "', description = " . quote_smart($this->adjustmentReason);
		$result = @mysql_query($query);
		$msg = "";
		if ($result) {
			$msg .= "Points have successfully been added.\n<br>";
			if ($this->sendMessage){
				$messageQuery = "INSERT INTO t_messages SET from_id = '" . $this->entryBy . "', to_id = '" . $this->driverid . "', subject = " . quote_smart($this->emailSubject) . ", message = " . quote_smart(nl2br($this->emailBody));
				$messageResult = @mysql_query($messageQuery);
				if ($messageResult) $msg .= "Message successfully sent to driver.\n<br>";
				else $msg .= "Error sending message to driver. If this error continues, please contact an administrator.";
			}
			if ($this->sendEmail){
				$getEmailQuery = "SELECT email FROM t_drivers WHERE driver_id = '" . $this->driverid . "'";
				$getEmailResult = mysql_query($getEmailQuery);
				if (mysql_num_rows($getEmailResult) == 1) {
					$driverEmail = mysql_result($getEmailResult, 0);
					if (!empty($driverEmail)) {
						if (@mail($driverEmail, $this->emailSubject, $this->emailBody, "From: transpo@web.uconn.edu")) $msg .= "Email successfully sent to " . $driverEmail . ".\n<br>";
						else $msg .= "Error sending email to driver. If this error continues, please contact an administrator.";
					} else $msg .= "Email not sent. No email address for this driver.";
				}
			}
		} else $msg .= "An error has occured. Please try again. If this error persists, please contact an administrator.";
		
		if ($this->resetFields) $this->resetData();
		
		return $msg;
	}
	
	function getErrors(){
		if ($this->errors) return $this->errors;
		else return false;
	}
	
	function resetData(){
		unset($this->driverid);
		unset($this->adjustmentReason);
		unset($this->points);
		unset($this->sendEmail);
		unset($this->sendMessage);
		unset($this->emailSubject);
		unset($this->emailBody);
	}
	
	function showErrors(){
		//echo "<ul>\n";
		//foreach($this->errors AS $error)
		//	echo "<li>" . $error . "</li>\n";
		//echo "</ul>";
		foreach($this->errors AS $error) echo $error . "<br>\n";
	}
	
	function setEnteredBy($id) { $this->entryBy = $id; }
	
	function getDriverID(){ return $this->driverid; }
	function getReason() { return $this->adjustmentReason; }
	function getPoints() { 
		if ($this->points == "" || $this->points == "0") return "0.00";
		else return $this->points;
	}
	function getResetFields() { if($this->resetFields) return " checked"; }
	function getSendMessage() { if($this->sendMessage) return " checked"; }
	function getSendEmail() { if ($this->sendEmail) return " checked"; }
	function getSubject() { return $this->emailSubject; }
	function getBody() { return $this->emailBody; }
	
}

/***************************************************************/
/* Class PointsPayPeriod - This class is used to easily add    */
/* points for drivers earned during each pay period            */
/***************************************************************/

class PointsPayPeriod {
	var $singlePoints;
	var $doublePoints;
	var $triplePoints;
	var $quadruplePoints;
	var $payPeriod;
	var $errors; 
	var $entryBy;
	
	function displayActiveDriverForm(){
		$query = "SELECT * FROM t_drivers WHERE (active = '1' AND durational = '0'" . EXCLUDE_QUERY . ") ORDER BY lastname ASC";
		$result = mysql_query($query);
		$totalDrivers = mysql_num_rows($result);
		$i = 0;
		while ($data = mysql_fetch_array($result)){
			$i++;
			echo "<tr id=\"row" . $data['driver_id'] . "\"";
			if ($this->errors[$data['driver_id']]) echo " style=\"background-color: #FFCCCC\"";
			echo ">\n";
			echo "<td>" . $data['lastname'] . ", " . $data['firstname'] . "</td>\n";
			echo "<td align=\"center\"><input type=\"text\" value=\"" . $this->singlePoints[$data['driver_id']] . "\" onchange=\"totalDriverPoints(" . $data['driver_id'] . ")\" tabindex=\"" . $i . "\" name=\"points[" . $data['driver_id'] . "]\" size=\"6\"></td>\n";
			echo "<td align=\"center\"><input type=\"text\" value=\"" . $this->doublePoints[$data['driver_id']] . "\" onchange=\"totalDriverPoints(" . $data['driver_id'] . ")\" tabindex=\"" . ($i + $totalDrivers) . "\"  name=\"doublePoints[" . $data['driver_id'] . "]\" size=\"6\"></td>\n";
			echo "<td align=\"center\"><input type=\"text\" value=\"" . $this->triplePoints[$data['driver_id']] . "\" onchange=\"totalDriverPoints(" . $data['driver_id'] . ")\" tabindex=\"" . ($i + ($totalDrivers * 2)) . "\"  name=\"triplePoints[" . $data['driver_id'] . "]\" size=\"6\"></td>\n";
			echo "<td align=\"center\"><input type=\"text\" value=\"" . $this->quadruplePoints[$data['driver_id']] . "\" onchange=\"totalDriverPoints(" . $data['driver_id'] . ")\" tabindex=\"" . ($i + ($totalDrivers * 3)) . "\"  name=\"quadruplePoints[" . $data['driver_id'] . "]\" size=\"6\"></td>\n";
			echo "<td align=\"center\"><span id=\"totalPoints" . $data['driver_id'] . "\">" . ($this->singlePoints[$data['driver_id']] + ($this->doublePoints[$data['driver_id']] * 2) + ($this->triplePoints[$data['driver_id']] * 3) + ($this->quadruplePoints[$data['driver_id']] * 4)) . "</td>";
			echo "</tr>\n";
		}
	}
	
	function getData(){
		$this->singlePoints = $_POST['points'];
		$this->doublePoints = $_POST['doublePoints'];
		$this->triplePoints = $_POST['triplePoints'];
		$this->quadruplePoints = $_POST['quadruplePoints'];
		$this->payPeriod = $_POST['payperiod'];
	}
	
	function insertData(){
		$desc = "Pay Period Ending " . date("F j, Y", $this->payPeriod);
		foreach($this->singlePoints AS $id => $value)
			if (!empty($value)) mysql_query("INSERT INTO t_seniority SET driver_id = '$id', points = '$value', entry_by = '" . $this->entryBy . "', description='" . $desc . "'");
		foreach($this->doublePoints AS $id => $value)
			if (!empty($value)) mysql_query("INSERT INTO t_seniority SET driver_id = '$id', points = '" . $value * 2 . "', entry_by = '" . $this->entryBy . "', description='" . $desc . " - Double Seniority Points'");
		foreach($this->triplePoints AS $id => $value)
			if (!empty($value)) mysql_query("INSERT INTO t_seniority SET driver_id = '$id', points = '" . $value * 3 . "', entry_by = '" . $this->entryBy . "', description='" . $desc . " - Triple Seniority Points'");
		foreach($this->quadruplePoints AS $id => $value)
			if (!empty($value))	mysql_query("INSERT INTO t_seniority SET driver_id = '$id', points = '" . $value * 4 . "', entry_by = '" . $this->entryBy . "', description='" . $desc . " - Quadruple Seniority Points'");
	}
	
	function displayPayPeriod(){
		echo "<select name=\"payperiod\">\n";
		$sevenDays = 60 * 60 * 24 * 7;
		$thisThursday = strtotime("Thursday");
		if (empty($this->payPeriod) || $this->payPeriod == 0) $this->payPeriod = $thisThursday;
		$it = 0;
		for ($i = 5; $i >= 1; $i--){
			$thurs = $thisThursday - ($i * $sevenDays);
			echo "<option value=\"" . $thurs . "\"";
			if ($this->payPeriod == $thurs) echo " selected";
			echo ">" . date("l F jS, Y", $thurs) . "</option>\n";
			$it++;
			if ($it > 10) break;
		}
		echo "<option value=\"" . $thisThursday . "\"";
		if ($this->payPeriod == $thisThursday) echo " selected";
		echo ">" . date("l F jS, Y", $thisThursday) . "</option>\n";
		echo "</select>";
	}
	
	function getErrors(){
		if ($this->errors) return $this->errors;
		else return false;
	}
	
	function validateData(){
		if($this->entryBy <= 0) $this->errors["noEntryBy"] = true;
		$noData = true;
		foreach($this->singlePoints AS $id => $value) {
			if (!empty($value) AND !is_numeric($value)) $this->errors[$id] = true;
			if (!empty($value) AND is_numeric($value) AND $value != "0") $noData = false;
		}
		foreach($this->doublePoints AS $id => $value) {
			if (!empty($value) AND !is_numeric($value)) $this->errors[$id] = true;
			if (!empty($value) AND is_numeric($value) AND $value != "0") $noData = false;
		}
		foreach($this->triplePoints AS $id => $value) {
			if (!empty($value) AND !is_numeric($value)) $this->errors[$id] = true;
			if (!empty($value) AND is_numeric($value) AND $value != "0") $noData = false;
		}
		foreach($this->quadruplePoints AS $id => $value) {
			if (!empty($value) AND !is_numeric($value)) $this->errors[$id] = true;
			if (!empty($value) AND is_numeric($value) AND $value != "0") $noData = false;
		}
		if (empty($this->errors) AND !$noData) return true;
		else return false;
	}
	
	function setEnteredBy($id) { $this->entryBy = $id; }
}

/***************************************************************/
/* Class PointsHistory - This class is used display the point  */
/* history page                                                */
/***************************************************************/

class PointsHistory {
	var $errors;
	var $drivers;
	var $totalHistory;
	var $currentPage;
	var $historyOffset = 50;
	var $currentOffset;
	
	function getHistory(){
		$query = "SELECT *, date_format(timestamp, '%b %D, %Y %H:%i:%S') AS timestamp FROM t_seniority ORDER BY timestamp DESC LIMIT $this->currentOffset, $this->historyOffset";
		$result = mysql_query($query);
		$this->page = $page;
		if ($result) return $result;
		else return false;
	}
	
	function getTotalRows(){
		$query = "SELECT * FROM t_seniority";
		$result = mysql_query($query);
		$this->totalHistory = mysql_num_rows($result);
	}
	
	function setCurrentPage($page){
		$this->currentOffset = $page * $this->historyOffset - $this->historyOffset;
		if ($this->currentOffset % $this->historyOffset != 0 OR $this->currentOffset < 1 OR $offset >= $this->totalHistory) $this->currentOffset = 0;
		$this->currentPage = ($this->currentOffset + $this->historyOffset) / $this->historyOffset;
	}
	
	function driverList(){
		$query = "SELECT driver_id, lastname, firstname FROM t_drivers";
		$result = mysql_query($query);
		while($data = mysql_fetch_array($result)){
			$id = $data['driver_id'];
			$fn = substr($data['firstname'], 0, 1) . ".";
			$ln = $data['lastname'];
			$this->drivers[$id] = $fn . " " . $ln;
		}
	}
	
	function showHistory(){
		if ($this->currentPage < 1) $this->currentPage = 1;
		$this->driverList();
		$historyResult = $this->getHistory($page);
		if (!$historyResult) echo "<p class=\"error\">Error retrieving data. Please try again. If this error persists, please contact an administrator.";
		else {
			$i = ($this->currentPage * $this->historyOffset) - $this->historyOffset + 1;
			while ($historyData = mysql_fetch_array($historyResult)){
				$driverid = $historyData['driver_id'];
				$entryby = $historyData['entry_by'];
				echo "<tr><td nowrap=\"nowrap\">" . $i . ") " . $this->drivers[$driverid] . "</td><td nowrap=\"nowrap\">" . $this->drivers[$entryby] . "</td><td align=\"center\">" . number_format($historyData['points'], 2) . "</td><td>" . $historyData['description'] . "</td><td align=\"center\">" . $historyData['timestamp'] . "</td></tr>\n";
				$i++;
			}
		}
	}
	
	function showButtons(){
		$totalPages = ceil($this->totalHistory / $this->historyOffset);
		if ($totalPages != 1){
			if ($this->totalPages != 1 AND $this->currentPage != 1) echo "<a href=\"?seniority=history&page=" . ($this->currentPage - 1) . "\">PREV</a> ";
			for ($i = 1; $i <= $totalPages; $i++) {
				if ($this->currentPage == $i) echo "<span style=\"color: #FF0000\">" . $i . "</span> ";
				else echo "<a href=\"?seniority=history&page=" . $i . "\">" . $i . "</a> ";
			}
			if ($this->totalPages != 1 AND $this->currentPage != $totalPages) echo "<a href=\"?seniority=history&page=" . ($this->currentPage + 1) . "\">NEXT</a> ";
		}
	}
	
	function setOffset($offset){ $this->historyOffset = $offset; }
}
?>
<style type="text/css">
.error {
	color: #CC0000;
	margin-bottom: 20px;
}
</style>
